<?php

namespace App\Repositories\Eloquent\Edu;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;
use Illuminate\Support\Facades\Storage;

use App\Repositories\Eloquent\Mgt\UserRepository as User;
use App\Repositories\Eloquent\Edu\TermRepository as Term;
use App\Repositories\Eloquent\Edu\DeployRepository as Deploy;
use App\Repositories\Eloquent\Edu\ClaseRepository as Clase;
use DB;

class TuserRepository extends Repository
{

    protected $user, $term, $deploy, $clase;

    public function __construct(App $app, User $user, Term $term, Deploy $deploy, Clase $clase)
    {
        parent::__construct($app);

        $this->user = $user;

        $this->term = $term;

        $this->deploy = $deploy;

        $this->clase = $clase;
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Edu\Tuser';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

    }


    /**
     * 微信前端报名
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function sign($request)
    {

        $ishandin = $request->ishandin;
        if( $ishandin){
            if( !$request->hasFile('files') )
                return $this->responseFail(403, '请上传作品或公益证书');

        }

        $user = $this->user->show($request->uid);

        $deploy = $this->deploy->show($request->deploy);

        if( $deploy->status !== STATUS_NORMAL ){
            return $this->responseFail(405, '报名数据错误');
        }

        if(empty($request->clase))
            return $this->responseFail(403, '请选择需要报名的课程');

        $clase = $this->clase->show($request->clase);
        if( $clase->is_limited == 1 && count($clase->enrolled)>=$clase->number)
            return $this->responseFail(406, '该班名额已满');

        $count = $this->model->where('uid', $user->id)->where('deploy_id', $deploy->id)->count();
        if( $deploy->limit !== 0 && $count >= $deploy->limit )
            return $this->responseFail(406, '您本次报名的课程已报满');

        $number = $this->model->where('uid', $user->id)->where('clase_id', $request->clase)->get();
        if ( count($number) > 0 )
            return $this->responseFail(406, '重复报名');

        DB::beginTransaction();
        try {

            $tuser = $this->store($request, $user, $clase);

            //附件上传
            if( $request->hasFile('files') ){

                $dir = public_path().'/uploads/'.date('Ymd').'/';

                $files = $request->file('files');

                foreach ($files as $file) {

                    $entension = $file->getClientOriginalExtension();

                    $filename = $user->account.'_'.mt_rand(100000,999999).'.'.$entension;

                    $file->move($dir,$filename);

                    $fullname = '/uploads/'.date('Ymd').'/'.$filename;

                    //写库
                    $attach = new \App\Models\Edu\Attachment;
                    $attach->tuser_id = $tuser->id;
                    $attach->file = $fullname;
                    $attach->save();
                }
            }

            DB::commit();
            return $this->responseSuccess('报名成功', $clase, route('wx.my.deploy'));

        } catch (Exception $e) {
            DB::rollback();
            return $this->responseFail(500, '报名失败');
        }

        /*if( !!$this->store($request, $user, $clase) )
            return $this->responseSuccess('报名成功', $clase, route('wx.index'));

        return $this->responseFail(500, '报名失败');*/

    }


    public function attachmentAdd($request)
    {
        $tuser = $this->show($request->tuser);

        DB::beginTransaction();
        try {

            //附件上传
            if( $request->hasFile('files') ){

                $dir = public_path().'/uploads/'.date('Ymd').'/';

                $files = $request->file('files');

                foreach ($files as $file) {

                    $entension = $file->getClientOriginalExtension();

                    $filename = $tuser->account.'_'.mt_rand(100000,999999).'.'.$entension;

                    $file->move($dir,$filename);

                    $fullname = '/uploads/'.date('Ymd').'/'.$filename;

                    //写库
                    $attach = new \App\Models\Edu\Attachment;
                    $attach->tuser_id = $tuser->id;
                    $attach->file = $fullname;
                    $attach->save();
                }
            }

            DB::commit();

            return $this->responseSuccess('上传成功', $tuser, route('wx.my.attachment',$tuser->id));

        } catch (Exception $e) {
            DB::rollback();
            return $this->responseFail(500, '上传失败');
        }
    }



    public function attachmentRemove($request)
    {
        $att = \App\Models\Edu\Attachment::findOrFail($request->attid);

        $path = public_path().$att->file;

        unlink($path);

        $att->delete();

        return $this->responseSuccess('删除成功', $att, route('wx.my.attachment',$request->tuser));
    }


    /**
     * 后台手工输入报名
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function add($request)
    {
        $user = \App\Models\Mgt\User::find($request->uid);
        if(!$user)
            return $this->responseFail(404,'用户账号信息不正确');


        if(empty($request->clase))
            return $this->responseFail(403, '请选择需要报名的课程');

        $clase = $this->clase->show($request->clase);
        if( $clase->is_limited == 1 && count($clase->users)>=$clase->number)
            return $this->responseFail(406, '该班名额已满');


        $number = $this->model->where('uid', $user->id)->where('clase_id', $request->clase)->get();
        if ( count($number) > 0 )
            return $this->responseFail(406, '重复报名');


        if( !!$this->store($request, $user, $clase) )
            return $this->responseSuccess('报名成功');

        return $this->responseFail(500, '报名失败');

    }


    public function store($request, $user, $clase)
    {
        $result = $this->create([
            'deploy_id' => $request->deploy,
            'type_id' => $clase->type->id,
            'term_id' => $clase->term->id,
            'category_id'=>$clase->category->id,
            'clase_id' => $clase->id,
            'branch_id' => $clase->branch->id,
            'uid' => $user->id,
            'account' => $user->account,
            'source' => $request->source,
            'status' => $clase->is_limited == 1?2:1, ////额满限招班一旦报名就确认录取
        ]);

        return $result;
    }


    public function deploy($user)
    {
        $result = $this->model
            ->with('term','branch','type','clase','category')
            ->where('uid', $user->id)
            ->get();

        return collection($result->toArray())->groupBy('term.name');
    }


    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $tuser = $this->find($id);

        if (!$tuser) {
            return $this->responseFail(404);
        }

        return $tuser;
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function renew($request, $id)
    {

    }


    public function status($request)
    {
        $tusers = $request->tusers;
        if( empty($tusers))
            return $this->responseFail(405, '请选择用户!');


        DB::beginTransaction();
        try {
            $result = $this->updateIn([
                'status' => $request->status,
            ], $tusers);

            DB::commit();

            return $this->responseSuccess('报名状态设置成功!', $result, route('train.users', $request->term));

        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500, '报名状态设置失败!');
        }
    }


    public function att($id)
    {
        $tuser = $this->show($id);

        $attachments = $tuser->attachments;

        return $attachments;
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->delete($id);

        return $this->responseSuccess('报名取消成功!', $id, route('wx.my.deploy'));
    }


}